<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body class="login-page">
<div class="login-container">
    <h1>用户登录</h1>
    <form id="loginForm">
        <input type="text" id="username" placeholder="用户名" required>
        <input type="password" id="password" placeholder="密码" required>
        <button type="submit">登录</button>
    </form>
    <p id="loginMessage" class="message"></p>
    <p>没有账号？<a href="register.html">立即注册</a></p>
</div>

<script>
    const loginForm = document.getElementById("loginForm");
    const loginMessage = document.getElementById("loginMessage");

    loginForm.addEventListener("submit", async (e) => {
        e.preventDefault();
        const username = document.getElementById("username").value;
        const password = document.getElementById("password").value;

        try {
            const response = await fetch("http://127.0.0.1:36985/api/v1/users/login", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ username, password }),
            });

            if (!response.ok) throw new Error("登录失败");

            const result = await response.json();
            localStorage.setItem("user", JSON.stringify(result.user)); // 保存用户信息
            window.location.href = "index.html"; // 跳转到主页面
        } catch (error) {
            loginMessage.textContent = "登录失败：" + error.message;
        }
    });
</script>
</body>
</html>